package com.zxl.template.view.pop;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.Animation;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.zxl.template.App;
import com.zxl.template.R;
import com.zxl.template.activity.ContactAty;
import com.zxl.template.http.JsonCallback;
import com.zxl.template.model.Contact;
import com.zxl.template.model.ContactRows;
import com.zxl.template.model.Dept;
import com.zxl.template.model.DocRows;
import com.zxl.template.model.MsgEvent;
import com.zxl.template.model.Receipt;
import com.zxl.zlibrary.tool.LActivityTool;
import com.zxl.zlibrary.tool.LEmptyTool;
import com.zxl.zlibrary.tool.LToast;
import com.zxl.zlibrary.tool.LogTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import mehdi.sakout.fancybuttons.FancyButton;
import okhttp3.Call;
import razerdp.basepopup.BasePopupWindow;

/*
 * @created by LoveLing on 2018/11/23
 * @emil 1079112877@qq.com
 * description: 流程POP
 */
public class FlowPop extends BasePopupWindow {

    private Context mContext;
    private RecyclerView rvFlow;
    List<Receipt.ChildFlows> childFlows;
    private FancyButton btnFlow;
    private List<ContactRows> contactRows = new ArrayList<>();

    private Map<Integer, List<ContactRows>> mMap;

    private int position = -1;
    private RvAdapter rvAdapter;
    private Receipt mReceipt;
    private DocRows docRows;
    private Refresh refresh;

    @SuppressLint("UseSparseArrays")
    public FlowPop(Context context, List<Receipt.ChildFlows> childFlows, Receipt receipt, DocRows docRows) {
        super(context);
        this.mContext = context;
        this.childFlows = childFlows;
        this.mReceipt = receipt;
        this.docRows = docRows;
        mMap = new HashMap<>();
        initView();
    }

    /**
     * @param contactRows
     */
    public void fresh(List<ContactRows> contactRows) {
        this.contactRows.clear();
        this.contactRows.addAll(contactRows);
        mMap.put(position, contactRows);
        rvAdapter.notifyDataSetChanged();

    }


    private void initView() {
        rvFlow = findViewById(R.id.rv_flow);
        btnFlow = findViewById(R.id.btn_flow);

        findViewById(R.id.iv_close).setOnClickListener(v -> this.dismiss());

        rvFlow.setLayoutManager(new LinearLayoutManager(mContext));
        rvAdapter = new RvAdapter(childFlows);
        rvFlow.setAdapter(rvAdapter);

        rvAdapter.setOnItemClickListener((adapter, view, position) -> {
            Receipt.ChildFlows item = (Receipt.ChildFlows) adapter.getItem(position);
            assert item != null;
            this.position = position;
            mMap.put(position, contactRows);
            LActivityTool.startActivity(ContactAty.class);
        });

        btnFlow.setOnClickListener(v -> {
            if (mMap.size() <= 0) {
                LToast.warning("至少选择一个流程.");
                return;
            }

            if (LEmptyTool.isEmpty(docRows) || LEmptyTool.isEmpty(mReceipt)) {
                return;
            }

            StringBuilder keys = new StringBuilder();
            StringBuilder values = new StringBuilder();
            for (Map.Entry<Integer, List<ContactRows>> entry : mMap.entrySet()) {
                for (ContactRows crs : entry.getValue()) {
                    values.append(",");
                    values.append(crs.userId);

                    keys.append(",");
                    keys.append(childFlows.get(entry.getKey()).childFlowId);
                }
            }

            if (keys.length() > 0)
                keys.deleteCharAt(0);
            if (values.length() > 0)
                values.deleteCharAt(0);

            LogTool.e(keys.toString() + "\n" + values.toString());

            ProgressDialog progressDialog = ProgressDialog.show(mContext, "", "正在操作...", true);
            App.mApp.mApi.saveJobs(this, docRows.documentId, docRows.handleId, values.toString(), keys.toString(), new JsonCallback<String>() {
                @Override
                public void onError(Call call, Exception e, int i) {
                    LogTool.e(e.getMessage());
                    LToast.warning(e.getMessage());
                    progressDialog.dismiss();
                }

                @Override
                public void onResponse(String s, int i) {
                    progressDialog.dismiss();
                    LToast.success("流转成功.");
                    EventBus.getDefault().post(new MsgEvent<>("refresh_doc_list", ""));
                    dismiss();
                    refresh.reFresh();
                }
            });


        });

    }


    @Override
    protected Animation onCreateDismissAnimation() {
        return null;
    }

    public interface Refresh {
        void reFresh();
    }

    public void setRefresh(Refresh refresh) {
        this.refresh = refresh;
    }


    @Override
    public View onCreateContentView() {
        return createPopupById(R.layout.pop_flow);
    }


    class RvAdapter extends BaseQuickAdapter<Receipt.ChildFlows, BaseViewHolder> {

        RvAdapter(List<Receipt.ChildFlows> childFlows) {
            super(R.layout.item_flow, childFlows);
        }

        @Override
        protected void convert(BaseViewHolder helper, Receipt.ChildFlows item) {
            helper.setText(R.id.tv_name, item.flowName);

            List<ContactRows> contactRows = mMap.get(helper.getPosition());
            if (LEmptyTool.isNotEmpty(contactRows)) {
                StringBuilder sb = new StringBuilder();
                for (ContactRows cr : contactRows) {
                    sb.append(",");
                    sb.append(cr.userCnName);
                }
                if (sb.length() > 0)
                    sb.deleteCharAt(0);
                helper.setText(R.id.tv_click, sb.toString());
            }

        }

    }
}
